/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.registration.web;

import com.registration.ManagedBean;
import com.registration.core.*;
import com.registration.membership.Member;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import static org.apache.commons.lang.StringUtils.isBlank;

/**
 * @date May 10, 2012
 *
 * @author ggutierrez
 */
public class RegistrationBean extends ManagedBean {

    private Attendee attendee;
    private List<Country> countries;
    private List<Category> categories;
    private List<Hotel> hotels;
    private Member member;
    private Hotel hotel;
    private List<Attendee> heads;
    private List<Attendee> leaders;
    private List<PaymentMethod> paymentMethods;
    private List<RoomPlan> roomPlans;

    public RegistrationBean() {
    }

    @Override
    public void reset() {
        attendee = new Attendee();
        member = null;
        super.reset();
    }

    @Override
    public String cancel() {
        return "success";
    }

    public String init() {
        reset();
        attendee = new Attendee();
        countries = getManager().findCountries();
        categories = getManager().findCategories(false);
        hotels = getManager().findHotels();
        member = null;
        heads = getManager().findHeads();
        leaders = getManager().findLeaders();
        paymentMethods = getManager().findPaymentMethods();
        roomPlans = getManager().findRoomPlans();
        return "success";
    }

    public String save() {
        if (attendee != null) {
            if (isBlank(attendee.getFirstName())) {
                addErrorMessage("Primer nombre es requerido");
                return "fail";
            }
            if (isBlank(attendee.getLastName())) {
                addErrorMessage("Primer apellido es requerido");
                return "fail";
            }
            if (isBlank(attendee.getEmail())) {
                addErrorMessage("Correo es requerido");
                return "fail";
            }
            if (attendee.getCategory() == null) {
                addErrorMessage("La categoria de participacion es requerida");
                return "fail";
            }
            if (attendee.getResidence() == null) {
                addErrorMessage("El pais de residencia es requerido");
                return "fail";
            }

            if (attendee.getCountry() != null && !attendee.getResidence().getName().equals("Nicaragua")) {
                if (attendee.isNeedTransportation()) {
                    if (attendee.getLodging() != null) {
                        if (attendee.getLodging().getArrivalDate() == null) {
                            addErrorMessage("Por favor informe la FECHA de su llegada");
                            return "fail";
                        }
                        if (attendee.getLodging().getArrivalTime() == null) {
                            addErrorMessage("Por favor informe la HORA de su llegada");
                            return "fail";
                        }
                        if (attendee.getLodging().getTerminal() == null) {
                            addErrorMessage("Por favor informe la TERMINAL");
                            return "fail";
                        }
                        if (isBlank(attendee.getLodging().getTerminalDescription())) {
                            addErrorMessage("Por favor informe la DESCRIPCION del transporte");
                            return "fail";
                        }
                    } else {
                        addErrorMessage("Por favor informe datos de su llegada");
                        return "fail";
                    }
                }
                /* if (attendee.getLodging().getHotel() == null) {
                 addErrorMessage("Por favor informe el lugar de hospedaje");
                 return "fail";
                 } */
            }
            if (attendee.getCategory().isRequiresValidation()) {
                if (!isBlank(attendee.getMemberId())) {
                    member = getManager().loadMember(attendee.getMemberId());
                    if (member != null) {
                        attendee.setMemberVerification(MemberVerification.VERIFICADO);
                    } else {
                        attendee.setMemberVerification(MemberVerification.PENDIENTE_VERIFICACION);
                    }
                } else {
                    attendee.setMemberVerification(MemberVerification.PENDIENTE_VERIFICACION);
                }
            } else {
                attendee.setMemberVerification(MemberVerification.NO_REQUIERE_VERIFICACION);
            }
            String fullName = attendee.getFirstName() + " " + attendee.getMiddleName() + " " + attendee.getLastName() + " " + attendee.getSecondLastName();
            attendee.setFullName(fullName);

            List<Attendee> existings = getManager().findAttendeesByCode(attendee.getFirstName(), null, attendee.getLastName(), null, null, attendee.getCategory(), null, null, null);

            if (existings != null && !existings.isEmpty() && existings.get(0) != null) {
                addErrorMessage("Ya existe un registro de participante con ese nombre y apellido para esa categoría");
                return "fail";
            } else {
                if (!isBlank(attendee.getMemberId())) {
                    existings = getManager().findAttendees(null, null, null, null, attendee.getMemberId(), "", "", null, null, null);
                    if (existings != null && !existings.isEmpty() && existings.get(0) != null) {
                        addErrorMessage("Ya existe un registro de participante con ese numero de miembro");
                        return "fail";
                    }
                }
            }

            SecureRandom prng;
            String confirmationNumber;
            try {
                prng = SecureRandom.getInstance("SHA1PRNG");
                confirmationNumber = new Integer(prng.nextInt(99999)).toString();
            } catch (NoSuchAlgorithmException ex) {
                confirmationNumber = new Long(Calendar.getInstance(TimeZone.getDefault()).getTime().getTime()).toString();
                Logger.getLogger(RegistrationBean.class.getName()).log(Level.SEVERE, null, ex);
            }

            attendee.setConfirmationNumber(confirmationNumber);
            if (attendee.getCategory() != null) {
                attendee.setCost(attendee.getCategory().getCost());
                attendee.setFinalCost(attendee.getCategory().getCost());
            }

            getManager().store(attendee);
            ((ConfirmationBean) lookup("confirmationBean")).startup(attendee);
        }
        return "success";
    }

    public void checkMembership(ValueChangeEvent e) throws AbortProcessingException {
        if (attendee != null && !isBlank(attendee.getMemberId())) {
            member = getManager().loadMember(attendee.getMemberId());
            if (member != null) {
                attendee.setMemberVerification(MemberVerification.VERIFICADO);
            } else {
                attendee.setMemberVerification(MemberVerification.PENDIENTE_VERIFICACION);
            }
            FacesContext.getCurrentInstance().renderResponse();
        }
    }

    public Attendee getAttendee() {
        return attendee;
    }

    public void setAttendee(Attendee attendee) {
        this.attendee = attendee;
    }

    public List<Country> getCountries() {
        return countries;
    }

    public void setCountries(List<Country> countries) {
        this.countries = countries;
    }

    public List<Category> getCategories() {
        return categories;
    }

    public void setCategories(List<Category> categories) {
        this.categories = categories;
    }

    public List<Hotel> getHotels() {
        return hotels;
    }

    public void setHotels(List<Hotel> hotels) {
        this.hotels = hotels;
    }

    public Member getMember() {
        return member;
    }

    public void setMember(Member member) {
        this.member = member;
    }

    public Hotel getHotel() {
        return hotel;
    }

    public void setHotel(Hotel hotel) {
        this.hotel = hotel;
    }

    public List<Attendee> getHeads() {
        return heads;
    }

    public void setHeads(List<Attendee> heads) {
        this.heads = heads;
    }

    public List<Attendee> getLeaders() {
        return leaders;
    }

    public void setLeaders(List<Attendee> leaders) {
        this.leaders = leaders;
    }

    public List<PaymentMethod> getPaymentMethods() {
        return paymentMethods;
    }

    public void setPaymentMethods(List<PaymentMethod> paymentMethods) {
        this.paymentMethods = paymentMethods;
    }

    public List<RoomPlan> getRoomPlans() {
        return roomPlans;
    }

    public void setRoomPlans(List<RoomPlan> roomPlans) {
        this.roomPlans = roomPlans;
    }
}
